<template>
  <div class="good-view-container">
    <div class="good-info">
        <div class="main-box">
            <div class="product-layout">
                <!-- 左侧图片区域 -->
                <div class="image-section">
                    <div class="image-container">
                        <img :src="baseApi + good.imgs" :alt="good.name" class="product-image" />
                        <div class="image-overlay">
                            <i class="iconfont icon-chakan"></i>
                        </div>
                    </div>
                </div>

                <!-- 右侧详情区域 -->
                <div class="detail-section">
                    <!-- 商品标题 -->
                    <div class="product-header">
                        <h1 class="product-title">{{ good.name }}</h1>
                        <p class="product-description">{{ good.description }}</p>
                    </div>

                    <!-- 价格信息 -->
                    <div class="price-section">
                        <div class="price-box" v-if="good.discount < 1">
                            <div class="price-item">
                                <span class="price-label">原价</span>
                                <span class="original-price">￥{{ price }}</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label">折扣</span>
                                <span class="discount-badge">{{ discount }}</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label">现价</span>
                                <span class="current-price">￥{{ realPrice }}</span>
                            </div>
                        </div>
                        <div class="price-box" v-if="good.discount === 1">
                            <div class="price-item">
                                <span class="price-label">价格</span>
                                <span class="current-price">￥{{ price }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- 商品信息 -->
                    <div class="product-info">
                        <div class="info-item">
                            <span class="info-label">月销量：</span>
                            <span class="info-value">{{ good.sales }}</span>
                        </div>
                        <div class="info-item" v-if="showStore">
                            <span class="info-label">库存：</span>
                            <span class="info-value">{{ store }}</span>
                        </div>
                    </div>

                    <!-- 规格选择 -->
                    <div class="specification-section" v-if="standards.length !== 0">
                        <h3 class="section-title">选择规格</h3>
                        <div class="specification-grid">
                            <el-radio-group
                                v-for="(standard, index) in standards"
                                v-model="checkedStandard"
                                @change="change(standard)"
                                :key="index"
                                class="specification-group"
                            >
                                <el-radio-button
                                    class="specification-button"
                                    :label="standard.value"
                                >{{ standard.value }}</el-radio-button>
                            </el-radio-group>
                        </div>
                    </div>

                    <!-- 数量选择 -->
                    <div class="quantity-section">
                        <h3 class="section-title">选择数量</h3>
                        <el-input-number
                            v-model="count"
                            controls-position="right"
                            :min="1"
                            :max="store"
                            class="quantity-input"
                        ></el-input-number>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="action-section">
                        <el-button
                            type="success"
                            @click="goToOrder"
                            class="action-button buy-button"
                        >
                            <i class="iconfont icon-r-yes"></i>
                            立即购买
                        </el-button>
                        <el-button
                            type="primary"
                            @click="addToCart"
                            class="action-button cart-button"
                        >
                            <i class="iconfont icon-r-add"></i>
                            加入购物车
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 评论区域 -->
    <div class="comments-section">
        <div class="comments-header">
            <h3>商品评价</h3>
            <div class="comments-stats" v-if="commentStats">
                <span class="total-comments">共 {{ commentStats.totalCount }} 条评价</span>
                <span class="avg-rating">
                    <el-rate 
                        :value="commentStats.avgRating" 
                        disabled 
                        show-score 
                        text-color="#ff9900"
                        score-template="{value}分"
                    />
                </span>
            </div>
        </div>
        
        <div class="comments-list">
            <div v-if="comments.length === 0" class="no-comments">
                <i class="el-icon-chat-dot-square"></i>
                <p>暂无评价，快来做第一个评价的人吧～</p>
            </div>
            <comment-item 
                v-for="comment in comments" 
                :key="comment.id" 
                :comment="comment"
            />
        </div>
        
        <div class="comments-pagination" v-if="comments.length > 0">
            <el-button @click="loadMoreComments" :loading="loadingComments">
                {{ loadingComments ? '加载中...' : '查看更多评价' }}
            </el-button>
        </div>
    </div>
  </div>
</template>

<script>
import API from "@/utils/request";
import CommentItem from "@/components/CommentItem.vue";

export default {
    name: "GoodView",
    components: {
        CommentItem
    },
    data() {
        return {
            baseApi: this.$store.state.baseApi,
            good: {},
            goodId: Number,
            price: -1,
            isDiscount: false,
            discount: "",
            standards: [],
            checkedStandard: "",
            store: 0,
            showStore: false,
            count: 1,
            // 评论相关数据
            comments: [],
            commentStats: null,
            loadingComments: false,
            commentsPage: 1,
            commentsSize: 10
        };
    },
    methods: {
        getPriceRange(standards) {
            let arr = standards.map((item) => {
                return item.price;
            });
            //选择排序
            for (let i = 0; i < arr.length; i++) {
                // 第一次循环，假设第一个值为最小值，后面i++依此类推
                let min = i;
                for (let j = i + 1; j < arr.length; j++) {
                    // 将第一个值循环与后面的值比较，如果后面的值比第一个值小，则将索引赋值给min，直到找到最小值
                    if (arr[j] < arr[min]) {
                        min = j;
                    }
                }
                [arr[i], arr[min]] = [arr[min], arr[i]];
            }
            if (arr[0] === arr[arr.length - 1]) {
                return arr[0];
            } else {
                return arr[0] + "元 ~ " + arr[arr.length - 1];
            }
        },
        change(standard) {
            this.showStore = true;
            this.price = standard.price;
            this.store = standard.store;
        },
        goToOrder() {
            if (this.standards.length !== 0) {
                if (this.checkedStandard === "") {
                    this.$message.warning("请选择规格");
                    return false;
                }
            }
            console.log(this.good);
            console.log(this.checkedStandard);
            this.$router.push({
                name: "preOrder",
                query: {
                    good: JSON.stringify(this.good),
                    realPrice: this.realPrice,
                    num: this.count,
                    standard: this.checkedStandard,
                },
            });
        },
        addToCart() {
            //未登录，拦截
            console.log(localStorage.getItem("user"));
            if (!localStorage.getItem("user")) {
                this.$router.push("/login");
            }
            if (!this.checkedStandard) {
                this.$message.error("请选择规格");
                return false;
            }
            // 从服务器获取当前用户的id，保证安全
            this.request.get("/userid").then((res) => {
                let userId = res;
                let cart = {
                    userId: userId,
                    goodId: this.goodId,
                    standard: this.checkedStandard,
                    count: this.count,
                };
                this.request.post("/api/cart", cart).then((res) => {
                    if (res.code === "200") {
                        this.$message.success("成功添加购物车");
                    }
                });
            });
        },
        
        // 加载评论列表
        async loadComments() {
            try {
                this.loadingComments = true;
                const response = await API.get(`/api/comment/good/${this.goodId}`);
                if (response.code === '200') {
                    this.comments = response.data;
                }
            } catch (error) {
                console.error('加载评论失败:', error);
            } finally {
                this.loadingComments = false;
            }
        },
        
        // 加载评论统计
        async loadCommentStats() {
            try {
                const response = await API.get(`/api/comment/statistics/${this.goodId}`);
                if (response.code === '200') {
                    this.commentStats = response.data;
                }
            } catch (error) {
                console.error('加载评论统计失败:', error);
            }
        },
        
        // 加载更多评论
        loadMoreComments() {
            // 这里可以实现分页加载更多评论
            this.$message.info('功能开发中，敬请期待');
        }
    },

    created() {
        //初始化商品信息
        // this.good = JSON.parse(this.$route.query.good)
        this.goodId = this.$route.params.goodId;
        this.request
            .get("/api/good/" + this.goodId)
            .then((res) => {
                if (res.code === "200") {
                    this.good = res.data;
                    let discount = this.good.discount;
                    if (discount < 1) {
                        this.isDiscount = true;
                        this.discount = discount * 10 + "折";
                    }
                } else {
                    this.$router.go(0);
                }
            })
            .catch((error) => {
                this.$message.error(error.response.data);
                console.log(error);
            });
        //从服务器获取商品规格信息
        this.request
            .get("/api/good/standard/" + this.goodId)
            .then((res) => {
                if (res.code === "200") {
                    let standards = JSON.parse(res.data);
                    this.standards = standards;
                    //默认选择第一个标准
                    this.price = this.getPriceRange(standards);
                } else {
                    //没有规格
                    this.price = this.good.price;
                    this.store = this.good.store;
                    this.showStore = true;
                }
                
            })
            .catch((error) => {
                this.$message.error(error.response.data);
                console.log(error);
                
            });
        
        // 加载评论数据
        this.loadComments();
        this.loadCommentStats();
    },
    mounted() {},
    computed: {
        //折后价，小数点后2位
        realPrice: function () {
            if (this.good.discount < 1) {
                //价格为范围，即不是数字，则返回一个范围
                if (isNaN(this.price)) {
                    let down =
                        this.price.substring(0, this.price.indexOf("元")) *
                        this.good.discount;
                    let up =
                        this.price.substring(this.price.lastIndexOf(" ")) *
                        this.good.discount;
                    return down.toFixed(2) + "元 ~ " + up.toFixed(2);
                } else {
                    return (this.price * this.good.discount).toFixed(2);
                }
            }
            return this.price;
        },
    },
};
</script>

<style scoped>
.good-view-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.main-box {
  max-width: 1200px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.product-layout {
  display: flex;
  gap: 40px;
  padding: 40px;
}

/* 左侧图片区域 */
.image-section {
  flex: 0 0 500px;
}

.image-container {
  position: relative;
  width: 500px;
  height: 500px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.image-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.image-container:hover .product-image {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.image-overlay i {
  color: #ffffff;
  font-size: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 20px;
  backdrop-filter: blur(10px);
}

/* 右侧详情区域 */
.detail-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.product-header {
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 20px;
}

.product-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 15px 0;
  line-height: 1.3;
}

.product-description {
  font-size: 16px;
  color: #666;
  margin: 0;
  line-height: 1.6;
}

/* 价格区域 */
.price-section {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
}

.price-box {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.price-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.price-item:last-child {
  border-bottom: none;
}

.price-label {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.original-price {
  font-size: 18px;
  color: #999;
  text-decoration: line-through;
}

.discount-badge {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
}

.current-price {
  font-size: 28px;
  font-weight: 700;
  color: #e74c3c;
}

/* 商品信息 */
.product-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.info-label {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  min-width: 80px;
}

.info-value {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

/* 规格选择 */
.specification-section {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 15px;
  padding: 25px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 20px 0;
}

.specification-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.specification-group {
  margin: 0;
}

.specification-button {
  height: 40px;
  padding: 0 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.specification-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

/* 数量选择 */
.quantity-section {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 15px;
  padding: 25px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.quantity-input {
  width: 150px;
}

.quantity-input .el-input-number__decrease,
.quantity-input .el-input-number__increase {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

/* 操作按钮 */
.action-section {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.action-button {
  flex: 1;
  height: 50px;
  font-size: 18px;
  font-weight: 600;
  border-radius: 25px;
  border: none;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.buy-button {
  background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
  color: white;
  box-shadow: 0 8px 25px rgba(46, 204, 113, 0.3);
}

.buy-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 15px 35px rgba(46, 204, 113, 0.4);
  background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
}

.cart-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.cart-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.action-button i {
  font-size: 20px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .product-layout {
    flex-direction: column;
    gap: 30px;
    padding: 30px;
  }
  
  .image-section {
    flex: none;
  }
  
  .image-container {
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
  }
}

@media (max-width: 768px) {
  .good-view-container {
    padding: 10px;
  }
  
  .main-box {
    border-radius: 15px;
  }
  
  .product-layout {
    padding: 20px;
    gap: 20px;
  }
  
  .product-title {
    font-size: 24px;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-button {
    height: 45px;
    font-size: 16px;
  }
  
  .image-container {
    height: 350px;
  }
}

@media (max-width: 480px) {
  .product-layout {
    padding: 15px;
  }
  
  .product-title {
    font-size: 20px;
  }
  
  .current-price {
    font-size: 24px;
  }
  
  .image-container {
    height: 300px;
  }
}

/* 评论区域样式 */
.comments-section {
  background: rgba(255, 255, 255, 0.95);
  margin: 20px;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.comments-header h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.comments-stats {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-comments {
  color: #666;
  font-size: 14px;
}

.avg-rating {
  display: flex;
  align-items: center;
}

.comments-list {
  margin-bottom: 20px;
}

.no-comments {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.no-comments i {
  font-size: 48px;
  margin-bottom: 15px;
  display: block;
}

.no-comments p {
  margin: 0;
  font-size: 16px;
}

.comments-pagination {
  text-align: center;
  padding: 20px 0;
}

.comments-pagination .el-button {
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comments-section {
    margin: 10px;
    padding: 20px;
  }
  
  .comments-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .comments-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>